package com.hyfrogx.modules.app.controller.zoom;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hyfrogx.common.exception.MyException;
import com.hyfrogx.common.utils.QueryExt;
import com.hyfrogx.common.utils.R;
import com.hyfrogx.common.validator.ValidatorUtils;
import com.hyfrogx.modules.app.annotation.Login;
import com.hyfrogx.modules.app.entity.User;
import com.hyfrogx.modules.app.service.UserService;
import com.hyfrogx.modules.app.utils.FrogConstant;
import com.hyfrogx.modules.zoom.entity.HyNmtPower;
import com.hyfrogx.modules.zoom.entity.HyPowerFb;
import com.hyfrogx.modules.zoom.entity.HyPowerOrder;
import com.hyfrogx.modules.zoom.entity.HyPowerUser;
import com.hyfrogx.modules.zoom.form.PowerFbForm;
import com.hyfrogx.modules.zoom.service.HyNmtPowerService;
import com.hyfrogx.modules.zoom.service.HyPowerFbService;
import com.hyfrogx.modules.zoom.service.HyPowerOrderService;
import com.hyfrogx.modules.zoom.service.HyPowerUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author ：Li9527
 * @date ：Created in 2019-11-19 9:52
 * @description：会议特权
 * @modified By：
 * @version: 1.0.0
 */
@RestController
@RequestMapping("/api/nmtPower")
@Api(value = "会议特权controller", tags = "客户端--会议特权")
public class ApiNmtPowerController {

    @Autowired
    HyNmtPowerService nmtPowerService;

    @Autowired
    HyPowerOrderService powerOrderService;

    @Autowired
    HyPowerUserService powerUserService;

    @Autowired
    UserService userService;

    @Autowired
    HyPowerFbService powerFbService;

    /**
     * 分页获取所有特权记录
     *
     * @param
     * @throws MyException
     */
    @ApiOperation("分页获取所有特权记录")
    @PostMapping("getList")
    @Login
    public R getList(@RequestParam Map<String, Object> params) {
        try {
            List<HyNmtPower> list = nmtPowerService.list(new QueryWrapper<HyNmtPower>().eq("status", FrogConstant.Status.TRUE));
            if (list.size() > 0) {
                for (HyNmtPower p : list) {
                    if (p.getTprice() >= 10000 && p.getTprice() != null) {
                        double newNum = p.getTprice() / 10000.0;
                        BigDecimal bd1 = new BigDecimal(newNum).setScale(2, BigDecimal.ROUND_DOWN);
                        p.setTpriceUnitWan(bd1.toString() + "万");
                    } else {
                        p.setTpriceUnitWan(p.getTprice().toString());
                    }
                    if (p.getPrice() >= 10000 && p.getPrice() != null) {
                        double newNum = p.getPrice() / 10000.0;
                        BigDecimal bd1 = new BigDecimal(newNum).setScale(2, BigDecimal.ROUND_DOWN);
                        p.setPriceUnitWan(bd1.toString() + "万");
                    } else {
                        p.setPriceUnitWan(p.getPrice().toString());
                    }
                }
                return R.ok().put("data",list);
            } else {
                return R.ok("暂无数据");
            }
        } catch (MyException e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 客户端购买特权,特权卡id和用户uid必传
     *
     * @param
     * @return Interage
     * @throws Exception
     */
    @Login
    @ApiOperation("客户端购买特权")
    @PostMapping("buyMntPower")
    public R buyMntPower(@RequestParam(value = "pid", required = true) Integer pid,
                         @ApiIgnore @RequestAttribute(value = "userId") Long uid) {
        try {
            // 后台购买时校验专属卡属性
            HyNmtPower power = nmtPowerService.getById(pid);
            if (power == null || power.getStatus() == 0) {
                return R.error("该特权卡不存在活被禁用");
            }
            // 判断特权卡是否专属
            if (power.getType() == 1) {
                return R.error("专属特权卡购买请联系三眼蛙客服人员");
            }
            // 创建订单
            HyPowerOrder record = new HyPowerOrder();
            record.setUid(uid);
            record.setPid(pid);
            Integer result = powerOrderService.createPowerOrder(record);
            if (result > 0) {
                return R.ok("购买成功");
            } else {
                return R.error("购买失败");
            }
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 分页获取我的购买记录
     *
     * @param
     * @return List<HyNmtPower>
     * @throws Exception
     */
    @ApiOperation("分页获取我的购买记录")
    @GetMapping("getPowerOrderList")
    @Login
    public R getPowerOrderList(@RequestParam Map<String, Object> params,
                               @ApiIgnore @RequestAttribute(value = "userId") Long uid) {
        try {
            params.put("uid",uid);
            Page page = powerOrderService.selectPageByConditions(new QueryExt(params));
            if (page.getRecords().size() > 0) {
                return R.ok().put ("data", page);
            } else {
                return R.error("暂无数据");
            }
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 分页获取我的特权
     *
     * @param
     * @return List<HyNmtPower>
     * @throws Exception
     */
    @ApiOperation("分页获取我的特权")
    @PostMapping("getMyPowerList")
    @Login
    public R getMyPowerList(@RequestParam Map<String, Object> params,
                            @ApiIgnore @RequestAttribute(value = "userId") Long uid) {
        try {
            // 查询出用户权益list
            List<HyPowerUser> list = powerUserService.list(new QueryWrapper<HyPowerUser>().eq("uid",uid));
            if (list.size() > 0) {
                // 遍历用户权益list
                Iterator<HyPowerUser> p = list.iterator();
                while (p.hasNext()) {
                    HyPowerUser pu = p.next();
                    // 如果是专属会议室但是没有zoomid就移除
                    if (pu.getType() == 1 && pu.getZoomId() == null) {
                        p.remove();
                    }
                }
            }
            // 分条计算过期时间
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getEnddate().getTime() < System.currentTimeMillis()) {
                    long oldMls = list.get(i).getEnddate().getTime() / 1000;
                    long nowMls = System.currentTimeMillis() / 1000;
                    long cell = nowMls - oldMls;
                    String ndate = cell / 86400 + "天前";
                    list.get(i).setOverdueDay(ndate);
                }
            }
            return R.ok().put("data",list);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }


    /**
     * 订单反馈,特权卡id和用户uid必传
     * @param
     * @return
     * @throws
     */
    @ApiOperation("订单反馈")
    @PostMapping("/feedback/add")
    @Login
    public R feedback(@RequestBody PowerFbForm fbForm, @ApiIgnore @RequestAttribute(value = "userId") Long uid) {
        try {
            ValidatorUtils.validateClientEntity(fbForm);
            HyNmtPower power = nmtPowerService.getById(fbForm.getPid());
            User u = userService.getUsersById(uid.intValue());
            if(ObjectUtil.isNull(power) || ObjectUtil.isNull(u) ){
                return R.error("用户不存在或者特权卡不存在");
            }
            HyPowerFb hyPowerFb = new HyPowerFb();
            BeanUtils.copyProperties(fbForm,hyPowerFb);
            // 手机号
            hyPowerFb.setUid(uid.intValue());
            hyPowerFb.setPhone(u.getPhone());
            hyPowerFb.setPid(power.getId());
            hyPowerFb.setName(power.getName());
            hyPowerFb.setCreateTime(new Date());
            Boolean result = powerFbService.save(hyPowerFb);
            if (result) {
                return R.ok("反馈成功");
            } else {
                return R.error("反馈失败");
            }
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }



}
